package com.home.cop.system;

import com.home.cop.sysinfo.model.UserSession;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Component
@Aspect
public class RequiredAuthAop {

    @Pointcut(value = "@annotation(com.home.cop.system.RequiredAuth)")
    public void requiredAuth(){}

    @Around("requiredAuth()")
    public Object tokenAuth(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //先直接从session中判断是否登录
        HttpSession session = request.getSession();
        UserSession userSession = (UserSession) session.getAttribute("userSession");
        if(userSession !=null && StringUtils.isNotBlank(userSession.getAccount())){
            return proceedingJoinPoint.proceed();
        }else {
            return Result.returnFail().setMessage("请登录！");
        }
    }
}
